例外処理 - JavaScript
Javaと同じ感覚で使える。try-catch, finally, throw
違うところ
エラーオブジェクトの型を書く必要がない
throwsの必要がない
エラーの名前を表すnameプロパティと内容を表すmessageプロパティを持つ
独自例外クラスを作るときはErrorを継承する
if (e instanceof RangeError) { ...
エラーオブジェクトのラップ
throw new Error("message", { cause: err });
独自例外クラスの作成
ベースはこんな感じ。これを継承したカスタムの例外クラスを作っていく
code:BaseError.ts
type BaseErrorOptions = {
message?: string;
cause?: unknown;
};
export class BaseError extends Error {
constructor(options: BaseErrorOptions) {
super(options?.message, { cause: options?.cause });
this.name = this.constructor.name;
}
}
this.name = this.constructor.name;
JavaScript例外の注意点:関数がどのような例外を送出するか判別できない
関数の仕様(ドキュメント)を見てtry-catch文を書く必要がある
JavaScriptで例外を積極的に使うかどうかはよく考える必要ありそう
参考文献
ビルトインエラー送出の例
たとえば関数の引数を文字列に限定したい場合
code:type-error.js
// 文字列を反転する関数
function reverseString(str) {
if (typeof str !== "string") {
throw new TypeError(${str} is not a string);
}
return Array.from(str).reverse().join("");
}
try {
// 数値を渡す
reverseString(100);
} catch (error) {
console.log(error instanceof TypeError); // => true
console.log(error.name); // => "TypeError"
console.log(error.message); // "100 is not a string"
}
console.error
エラーが発生した場合のコンソールへのメッセージ出力にconsole.errorを利用することでデバッグがしやすくなる
public.icon